package com.pricy.me.adapters;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.pricy.me.R;
import com.pricy.me.UserProfileActivity;
import com.pricy.me.model.Notification;
import com.pricy.me.utils.PrettyDate;

public class NotificationAdapter extends BaseAdapter{

	private List<Notification> data;
    private Context context;

    public NotificationAdapter(Context context, List<Notification> data) {
        this.context = context;
        this.data = data;
    }
    
	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Notification getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final Notification item = getItem(position);
        final ViewHolder holder;
		if (convertView == null) {
            LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = li.inflate(R.layout.notification_row, parent, false);
            holder = new ViewHolder();
            holder.ivUserpicture = (ImageView) convertView.findViewById(R.id.notification_userpicture);
            holder.tvNotification = (TextView) convertView.findViewById(R.id.notification_message);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
		
		String notification = "";
		if(item.getObject().equals("product_action_0")) notification = "<b>"+item.getUsername()+"</b> a indiqué que votre produit est une bonne affaire";
		else if(item.getObject().equals("product_action_1")) notification = "<b>"+item.getUsername()+"</b> possède aussi votre produit";
		notification += "<br/><i>"+ new PrettyDate(item.getDate()).toString()+"</i>";
		holder.tvNotification.setText(Html.fromHtml(notification));
		
		ImageLoader.getInstance().displayImage(item.getUserpicture(), holder.ivUserpicture);
		
		holder.ivUserpicture.setOnClickListener(userClicked);
		
		return convertView;
	}
	
	static class ViewHolder {
        ImageView ivUserpicture;
        TextView tvNotification;
    }
	
	OnClickListener userClicked = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			final Intent userProfile = new Intent(context, UserProfileActivity.class);
	    	context.startActivity(userProfile);
		}
	};
}
